import { ProList } from '@ant-design/pro-components';
import React, { useEffect, useState } from 'react';
import './index.less';
import { agents } from '@/services/ant-design-pro/api';

export type Agent = {
  id: string;
  name: string;
  image: string;
  desc: string;
};

interface AgentListProps {
  onChange: (value: Agent, reset: boolean) => void;
  agentId: string;
  sessionId: string;
}

const AgentList: React.FC = ({ onChange, agentId }: AgentListProps) => {
  const [dataSource, setDataSource] = useState<Agent[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);

  const handleRowClick = (record: Agent) => {
    console.log('Click on Agent row:', record);
    setSelectedRowKeys([record.id]);
    onChange(record, true);
  };

  useEffect(() => {
    agents({}).then((res) => {
      setDataSource(res.data);
    });
  }, []);

  useEffect(() => {
    if (agentId) {
      let agent = dataSource.find((item) => item.id == agentId);
      if (agent) {
        console.log('find agent by agent id', agent, agentId);
        onChange(agent, false);
        setSelectedRowKeys([agent.id]);
        return;
      }
    }
    let firstAgent = dataSource[0];
    onChange(firstAgent, false);
    setSelectedRowKeys([dataSource[0]?.id]);
  }, [dataSource]);

  return (
    <ProList<Agent>
      className={'agent-list'}
      rowKey="id"
      dataSource={dataSource}
      itemLayout="vertical"
      onRow={(record) => ({
        onClick: () => handleRowClick(record),
      })}
      rowSelection={{
        selectedRowKeys,
        renderCell: () => {
          return null;
        },
        onChange: (keys) => setSelectedRowKeys(keys as string[]),
      }}
      tableAlertRender={false}
      onDataSourceChange={setDataSource}
      metas={{
        title: {
          dataIndex: 'name',
        },
        avatar: {
          dataIndex: 'image',
          editable: false,
        },
        description: {
          dataIndex: 'description',
        },
      }}
    />
  );
};

export default AgentList;
